/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Controller;

import DB_MYSQL.MySqlConnection_Rd;
import DB_MYSQL.MySqlConnection_W;
import DB_MYSQL.Utils.DataRow;
import DB_MYSQL.Utils.DataTable;
import Model.ModelItem;
import Model.Request.ClientRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import libCore.Config;
import libCore.Util;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import share.ShareMacros;

/**
 *
 * @author LinhTA
 */
public class GiftController extends Controller {
    
    private static Logger logger_ = Logger.getLogger(ItemController.class);
    
    @Override  
    public void handle(ClientRequest request, HttpServletResponse resp) 
    {
         try {
            prepareHeader(resp);
            
            if(request._method.equals("get"))
                getGift(request, resp);
            else if(request._method.equals("send"))
                sendGift(request, resp);
            else if(request._method.equals("remove"))
                removeGift(request, resp);
            
        } catch (Exception ex) {
            logger_.error("Gift.handle:" + ex.getMessage() + ", Username:" + request._uid.toString(), ex);
        }
    }
    
    @Override
    protected JSONObject defaultResponse_False()
    {
       JSONObject data = new JSONObject();
       data.put(ShareMacros.SUSSCES, "false");
       List<Object> list = new ArrayList<Object>();
        data.put("list",list);
       return data;
    }
    
    public static boolean checkTimeSend(String uid,String fid,String appID, String item)
    {
        boolean check = false;
        
         long timeMin = 0;
        try
        {
            String t = Config.getParam(ShareMacros.INBOX_MIN, item);
            timeMin = Long.parseLong(t);
        }
        catch(Exception e)
        {
            
        }
        
        long timeNow = utilities.time.UtilTime.getTimeNow();
        
        long time = timeNow - timeMin;
        
        String where = "";
        where += ShareMacros.SENDER_ID_COL;
            where +=" = ";
            where += Util.quote(uid);    
            where += " AND ";
        where += ShareMacros.RECEIVER_ID_COL;
            where +=" = ";
            where +=Util.quote(fid);    
            where +=" AND ";
        where +=ShareMacros.APP_ID_COL;
            where +=" = ";
            where +=Util.quote(appID);    
            where +=" AND ";
        where +=ShareMacros.TIME_COL;
            where +=" > ";
            where +=Util.quote(String.valueOf(time));
            
         DataTable re = MySqlConnection_Rd.getInstance().selectCmdWhere(ShareMacros.INBOX_TABLE,where, ShareMacros.TIME_COL);    
         
         if(re.size() == 0)
             return true;
         
        return  check;
    }
   
    public void getGift(ClientRequest request , HttpServletResponse resp)
    {
      String appId = request._appId;
            String userId = request._uid;
            
            String condition = "";
            condition += share.ShareMacros.APP_ID_COL + " = " + Util.quote(appId);
            condition += " AND ";
            condition += share.ShareMacros.RECEIVER_ID_COL + " = " + Util.quote(userId);
            condition += " AND ";
            condition += share.ShareMacros.STATUS_COL + " = " + Util.quote(share.ShareMacros.STATUS_NOT_RECEIVED);
                        
            DataTable dt = MySqlConnection_Rd.getInstance().selectAllColumnCmdWhere(
                    share.ShareMacros.INBOX_TABLE, condition );
            
            String str = parseData(dt);
            
            //writer.print(str);
            //writer.flush();
            //writer.close();
            out(str, resp);
    }
    
    private String parseData(DataTable dt) {
        String dataStr  =   "{ \"isSuccess\": \"true\", \"list\":[";
        
        if( dt != null && dt.size() > 0 ) {
            int nsize = dt.size();
            for( int i = 0; i < nsize; ++i ) {
                DataRow dw  =   dt.get(i);
                
                String senderId = dw.get( share.ShareMacros.SENDER_ID_COL );
                senderId = Util.removePrefix(senderId);
                
                String itemId = dw.get(share.ShareMacros.ITEM_ID_COL);
                long count = Long.parseLong(dw.get(share.ShareMacros.COUNT_COL));
                long time = Long.parseLong(dw.get(share.ShareMacros.TIME_COL));
                
                Map<String, String> data    =   new HashMap<String, String>();
                data.put( ShareMacros.SENDER_ID_JSON, senderId );
                data.put( ShareMacros.ITEM_ID_JSON, itemId);
                data.put( ShareMacros.COUNT_JSON,String.valueOf( count));
                data.put( ShareMacros.TIME_JSON, String.valueOf(time));
                
                JSONObject mapJson = new JSONObject();
                mapJson.putAll(data);
                
                dataStr     =   dataStr + mapJson.toJSONString();
                if( i != ( nsize - 1 )) {
                    dataStr =   dataStr + ",";
                }
            }
        }
        
        dataStr     +=  "]}";
        return dataStr;
        
    }
    
    public void sendGift(ClientRequest request , HttpServletResponse resp)
    {
        String appId = request._appId;
            String itemId = request._data.get(ShareMacros.ITEM_ID_JSON);
            long count = Long.parseLong(request._data.get(ShareMacros.COUNT_JSON));
            String metadata = request._data.get(ShareMacros.META_DATA_JSON);
                    
            String senderId = request._uid;
            String receiverId = request._data.get(ShareMacros.RECEIVER_ID_JSON);
            if (request._meID == null || request._meID =="" || request._meID.isEmpty()) {
                receiverId = ShareMacros.PREFIX_FB + receiverId;
            } else {
                receiverId = ShareMacros.PREFIX_ME + receiverId;
            }
            
            //send by himself
            if (receiverId.equals(senderId)) {
                outFalse(resp);
                return;
            }
            
            if(!checkTimeSend(senderId, receiverId, appId, itemId))
            {
                outFalse(resp);
                return;
            }
            //('phamtanlong', 'nguyengiangchau', 'DBPTK', 0123456789, 'not_received', 'life', 1, '')
            String[] values  =   {
                Util.quote(senderId),
                Util.quote(receiverId),
                Util.quote(appId),
                "" + utilities.time.UtilTime.getTimeNow(),
                Util.quote(ShareMacros.STATUS_NOT_RECEIVED),
                Util.quote(itemId),
                "" + count,
                Util.quote(metadata),
            };
            int result = MySqlConnection_W.getInstance().insertTable( share.ShareMacros.INBOX_TABLE, share.ShareMacros.INBOX_COLUMNS, values );
            System.out.println( "__________SEND ITEM: " + result );
            
            String str = "{\"isSuccess\": \"true\"}";
            //writer.print(str);
            //writer.flush();
            //writer.close();
            out(str, resp);
            
    }
    
    public void removeGift(ClientRequest request , HttpServletResponse resp)
    {
        String appId = request._appId;
            String userId = request._uid;
            String senderId = request._data.get(ShareMacros.SENDER_ID_JSON);
            if (userId.startsWith(ShareMacros.PREFIX_FB)) {
                senderId = ShareMacros.PREFIX_FB + senderId;
            } else {
                senderId = ShareMacros.PREFIX_ME + senderId;
            }
            
            String item = request._data.get(ShareMacros.ITEM_ID_JSON);
            
            if(!ModelItem.checkAddItem(userId, item))
            {
                out("{\"isSuccess\": \"false\"}", resp);
            }
            
            long time = Long.parseLong(request._data.get(ShareMacros.TIME_JSON));
            
            String condition = "";
            condition += share.ShareMacros.APP_ID_COL + " = " + Util.quote(appId);
            condition += " AND ";
            condition += share.ShareMacros.RECEIVER_ID_COL + " = " + Util.quote(userId);
            condition += " AND ";
            condition += share.ShareMacros.SENDER_ID_COL + " = " + Util.quote(senderId);
            condition += " AND ";
            condition += share.ShareMacros.TIME_COL + " = " + Util.quote(String.valueOf(time));
            
            String[] colums =   { ShareMacros.STATUS_COL };
            String[] values  =   { Util.quote(ShareMacros.STATUS_REMOVED) };
            MySqlConnection_W.getInstance().updateTable( ShareMacros.INBOX_TABLE, colums, values, condition );
            
            String condition2 = condition + " AND "+ ShareMacros.STATUS_COL +" = "+Util.quote(ShareMacros.STATUS_REMOVED);
            DataTable dt = MySqlConnection_Rd.getInstance().selectAllColumnCmdWhere(
                    share.ShareMacros.INBOX_TABLE, condition2 );
            
            
            String str ="";
            if(dt.size()>0 )
            {
                if(ModelItem.addItem(userId, dt.get(0).get(ShareMacros.ITEM_ID_COL)))
                        str="{\"isSuccess\": \"true\"}";
                else
                    str="{\"isSuccess\": \"false\"}";
            }
             
            else
                str="{\"isSuccess\": \"false\"}";
            //writer.print(str);
            //writer.flush();
            //writer.close();
            out(str, resp);
    }
}
